import React, { useEffect, useState } from "react";
import http from "../../utils/http";
import { Swiper, Image, List, Toast } from "react-vant";
// import { useNavigate } from "react-router";
import ListItem from "../ListItem";
import "./index.css";
const Index = () => {
  const [bannerList, setBannerList] = useState([]);
  const [menu, setMenu] = useState([]);
  const [list, setList] = useState<any>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [finished, setFinished] = useState<boolean>(false);
  //   const navigate = useNavigate();
  //  轮播图
  const onFeachBanner = async () => {
    const banRes = await http.get("/api/banner");
    const { code, data } = banRes.data;
    if (code === 200) {
      setBannerList(data);
    }
  };
  //   Gird
  const onFeachMenu = async () => {
    const menuRes = await http.get("/api/menu");
    const { code, data } = menuRes.data;
    if (code === 200) {
      setMenu(data);
    }
  };

  //   上拉加载
  const onLoad = async () => {
    const listRes = await http.get("/api/list", {
      params: { currentPage, pageSize },
    });
    const { code, data } = listRes.data;
    if (code === 200) {
      // 修改页数
      setCurrentPage(currentPage + 1);
      // 合并数据
      setList([...list, ...data]);
    } else {
      setFinished(true);
      Toast.fail("没有更多数据了");
    }
  };
  useEffect(() => {
    onFeachBanner();
    onFeachMenu();
    onLoad();
  }, []);
  return (
    <div>
      {/* 轮播图 */}
      <Swiper>
        {bannerList.map((image) => (
          <Swiper.Item key={image}>
            <Image lazyload src={image} />
          </Swiper.Item>
        ))}
      </Swiper>
      {/* gird */}
      <div className="menu">
        {menu.map((item: any, ind) => (
          <div className="menu-item">
            <img src={item} alt="" key={ind} />
          </div>
        ))}
      </div>
      {/* 列表 */}
      <List finished={finished} onLoad={onLoad}>
        {list.length > 0 &&
          list.map((item: any, ind: number) => (
            <ListItem item={item} key={ind}></ListItem>
          ))}
      </List>
    </div>
  );
};

export default Index;
